import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from topsis import readData
from topsis.topsis_config import topsis_config

# 主执行函数
from topsis.topsis_main import topsis, topsis_rank


def clean_data(dataframe):
    dataframe = dataframe.mask(dataframe == '被冻结', 00000)
    dataframe = dataframe.fillna(0)
    dataframe = dataframe.drop_duplicates(subset=['uid'], keep='first')
    dataframe = dataframe.iloc[0:100, :]

    uid = dataframe.iloc[:, np.r_[0]]  # 获取第一列
    outcomes = dataframe[topsis_config.FIELDS_OUTCOME]  # 获取后面的列
    return uid, outcomes


def do_topsis(dataframe=None):
    sheet_name = 'bids_sheet'
    uid, dataset = clean_data(dataframe)
    result, rank_data = topsis_rank(uid, dataset)

    maxx = result['score'].max()
    w = 1 / maxx
    # minn = result['score'].min()
    # res = np.sqrt((result['score'] - minn) * w)
    # result['score'] = res
    result = result.rename(columns= {'id':'uid'})
    result['uid'] = result['uid'].astype(int)
    rank_data['uid'] = rank_data['uid'].astype(int)
    result['score'] = result['score'].apply(lambda x: format(x, '.3f')).astype(float)
    z = pd.merge(rank_data, result, on="uid")
    z = z.sort_values(by='score', ascending=False)
    writer = pd.ExcelWriter(topsis_config.Output_Dir + f'finalscore_allbids.xls')
    z.to_excel(writer, sheet_name='Sheet1')
    writer.save()
    axis1 = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
    axis2 = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95,
             1]
    # 拉伸分数
    result['score'] = result["score"] * w
    plt.hist(result['score'], bins=axis1, rwidth=0.5)
    # print(position_identify(result))

    plt.xlabel("分数")
    plt.ylabel("人数")

    #
    plt.show()
    # plt.savefig('bids_score.pdf',format='pdf')
    return


if __name__ == '__main__':
    data = pd.read_csv('allbidsinfo_zc.csv', encoding='utf-8')
    do_topsis(data)
